package edu.qqilin.springframework.beans.factory.support;

import edu.qqilin.springframework.beans.BeansException;
import edu.qqilin.springframework.beans.factory.BeanFactory;
import edu.qqilin.springframework.beans.factory.config.BeanDefinition;
import edu.qqilin.springframework.beans.factory.config.BeanPostProcessor;
import edu.qqilin.springframework.beans.factory.config.ConfigurableBeanFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: 工厂的抽象基类（总经理）。
 *
 * 实现了 getBean 的主流程（模板方法模式）：先查缓存 -> 没有则创建 (doGetBean)。
 *
 * @author qqilin1213
 * @version 1.0
 * @date 2025/11/22 16:13
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {

    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();


    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T) getBean(name);
    }

    protected <T> T doGetBean(final String name, final Object[] args) {
        // 1. 单例缓存中获取
        Object bean = getSingleton(name);
        if (bean != null) {
            return (T) bean;
        }
        // 2. 获取定义
        BeanDefinition beanDefinition = getBeanDefinition(name);
        // 3. 创建
        return (T) createBean(name, beanDefinition, args);
    }

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor){
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[]  args) throws BeansException;

    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return beanPostProcessors;
    }
}
